package lemna.top.chunyu.batch.step2;

import java.util.Date;

import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import lemna.top.chunyu.batch.config.ChunYunConfig;
import lemna.top.chunyu.batch.config.Constants;
import lemna.top.chunyu.batch.step2.domain.AlipayPaymentStatement;
 


@Configuration
public class Step2ReaderConfig {


	@Autowired
	ChunYunConfig config;

	@Autowired
	Resource step2File;
	
    @Bean 
    @StepScope
    public Resource step2File(@Value("#{jobParameters[date]}") Date date) {

		String dateParam = Constants.sdf1.format(date);
    	String filePath = config.getInputFilePath()+"alipay-"+dateParam+".csv";
        return new FileSystemResource(filePath);
    }

	@Bean(name="step2Reader")
	public FlatFileItemReader<AlipayPaymentStatement> step2Reader() {
		FlatFileItemReader<AlipayPaymentStatement> reader = new FlatFileItemReader<AlipayPaymentStatement>();
		reader.setResource(step2File);
//      reader.setResource(new FileSystemResource("d:/hu/cy/alipay-2017-07-26.csv"));
		reader.setEncoding("GBK");
		reader.setLinesToSkip(5);
		String[] comments = {"#"};
		reader.setComments(comments);
		reader.setLineMapper(new DefaultLineMapper<AlipayPaymentStatement>() {
			{
				setLineTokenizer(new DelimitedLineTokenizer() {
					{
						setNames(new String[] { "alipayTransactionNo", "merchantOrderNo", "businessType", "goodsName", "createTime", "completeTime", "storeNo", "storeName", "operator", "terminalNo", "reciprocalAccount", "orderAmount", "merchantIncome", "alipayRed", "jiFenBao", "alipayOffers", "merchantDiscount", "ticketAmount", "ticketName", "consumptionRed", "cardConsumptionAmount", "refundBatchNumber", "serviceCharge", "profit", "remarks"});
					}
				});
				setFieldSetMapper(new BeanWrapperFieldSetMapper<AlipayPaymentStatement>() {
					{
						setTargetType(AlipayPaymentStatement.class);
					}
				});
			}
		});
		return reader;
	}
}
